import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/cupertino.dart' hide Action;
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:www.znpigai.teacher/global_store/state.dart';
import 'package:www.znpigai.teacher/login_page/state.dart';
import 'package:www.znpigai.teacher/utils/http.dart';
import 'package:www.znpigai.teacher/utils/nav.dart';
import 'package:www.znpigai.teacher/utils/progress_dialog.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'state.dart';

Effect<SocialLoginState> buildEffect() {
  return combineEffects(<Object, Effect<SocialLoginState>>{
    Lifecycle.initState: _onInit,
    SocialLoginAction.onLogin: _onLogin,
    SocialLoginAction.onWeixin: _onWeixin,
    SocialLoginAction.onAgree: _onAgree,
    SocialLoginAction.onPrivate: _onPrivate,
  });
}

void _onInit(Action action, Context<SocialLoginState> ctx) {
  ctx.state.controller.initialize().then((_) {
    ctx.state.controller.setLooping(true);
    ctx.state.controller.play();
  });
}

void _onLogin(Action action, Context<SocialLoginState> ctx) {
  Navigator.of(ctx.context)
      .pushNamed(Nav.LOGIN, arguments: {"mode": LoginMode.LOGIN});
}

void _onWeixin(Action action, Context<SocialLoginState> ctx) async {
  fluwx.responseFromAuth.listen((response) async {
    if (response.errCode == 0) {
      // var pr = new ProgressDialog(ctx.context)..setMessage('请等待...');
      // pr.show();
      HttpResult result =
          await Http.post("/correct/join/api/third/login.mvc", data: {
        'loginType': 'wx',
        'identity': 'TEACHER',
        'code': response.code,
      });
      // pr.hide();

      if (result.success) {
        GlobalState.ticket = result.data;
        GlobalState.isSignIn = true;
        Navigator.of(ctx.context)
            .pushNamedAndRemoveUntil(Nav.HOME, (Route<dynamic> route) => false);
      } else {
        Util.alertFail(result, ctx.context);
      }
    }
  });
  fluwx.sendAuth(scope: "snsapi_userinfo", state: "wechat_sdk_demo_test");
}

void _onAgree(Action action, Context<SocialLoginState> ctx) {
  var url = "/correct/pub/view/agreement.mvc?type=2";
  Navigator.of(ctx.context).pushNamed(Nav.WEB_PAGE, arguments: {"url": url});
}

void _onPrivate(Action action, Context<SocialLoginState> ctx) {
  var url = "/correct/pub/view/agreement.mvc?type=3";
  Navigator.of(ctx.context).pushNamed(Nav.WEB_PAGE, arguments: {"url": url});
}
